package com.yaodian100.ec.timelimitsale;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.generate.entity.EventImage;
import com.yaodian100.ec.generate.service.GenerateService;
import com.yaodian100.ec.generatepage.web.GenerateHelper;
import com.yaodian100.ec.timelimitsale.entity.TimeLimitMain;
import com.yaodian100.ec.timelimitsale.entity.TimeLimitProd;
import com.yaodian100.ec.timelimitsale.service.TimeLimitSaleService;

/**
 * 限时抢购
 * 
 * @author apple.chang
 * 
 */
public class TimeLimitSaleAction extends ActionSupport implements Preparable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4361192705983283905L;

	private final Logger logger = LoggerFactory.getLogger(TimeLimitSaleAction.class);
	private final String imageFolder = "TIME_LIMIT_SALE";
	private TimeLimitSaleService timeLimitSaleService;
	private DomainService<Menu> menuService;
	private GenerateService generateService;
	private SimplePager pager = null;

	private List<TimeLimitMain> timeLimitMainList;
	private List<TimeLimitProd> timeLimitProdList;
	private String id;
	private String minDate;

	private String saleDate;
	private String name;
	private String[] is_repeat;
	private String[] is_limit_buy;
	private String[] imagePath;
	private File[] prodImg;
	private String[] productId;
	private String[] roundTag;
	private String[] productName;
	private String[] idxProductName;
	private String[] memberPrice;
	private String[] limitPrice;
	private String[] uploadImage;
	private String[] prodId;
	private String[] adWord;
	private EventImage eventImage = null;
	private String error;

	/******* 查询页面参数 ********/
	private String snameParam;
	private Menu showTypeMenu;
	private String sstartDateParam;
	private String sendDateParam;
	private String scategoryId;
	private String sshowTypeParam;

	@Override
	public void prepare() throws Exception {
		// TODO Auto-generated method stub
		clearErrorsAndMessages();

		if (null == pager) {
			pager = new SimplePager();
		}

		if (null == showTypeMenu) {
			showTypeMenu = menuService.get("TimeLimitSale.ShowType");
		}
		minDate = DateUtil.convertDateToString("yyyy,MM - 1,dd", new Date());
	}

	public String search() throws ParseException {

		// search value
		CommonCriteria crit = new CommonCriteria();

		if (StringUtils.isNotBlank(snameParam)) {
			crit.addRlike("name", snameParam);
		}
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		if (StringUtils.isNotBlank(sstartDateParam)) {
			Date sday = dateFormat.parse(sstartDateParam);
			crit.addGe("saleDate", sday);
		}
		if (StringUtils.isNotBlank(sendDateParam)) {
			Date eday = dateFormat.parse(sendDateParam);
			crit.addLe("saleDate", eday);
		}
		if (StringUtils.isNotBlank(scategoryId)) {
			crit.addEq("categoryID", Integer.parseInt("categoryID"));
		}
		if (StringUtils.isNotBlank(sshowTypeParam)) {
			Date now = new Date();
			now = dateFormat.parse(dateFormat.format(now));
			if (sshowTypeParam.equals("WAIT")) {
				crit.addGe("saleDate", now);
			} else if (sshowTypeParam.equals("ON")) {
				crit.addEq("saleDate", now);
			} else if (sshowTypeParam.equals("OVERDUE")) {
				crit.addLe("saleDate", now);
			}
		}
		crit.addNe("categoryID", -1);
		int contentSize = timeLimitSaleService.getListSize(crit).intValue();
		pager.setPageRecord(20);
		pager.setTotalSize(contentSize);
		timeLimitMainList = timeLimitSaleService.getList(pager.getCurrentPage() * pager.getPageRecord(), pager
				.getPageRecord(), crit, new String[] { "saleDate desc" });
		return "list";
	}

	public String add() {
		error = null;
		minDate = DateUtil.convertDateToString("yyyy,MM - 1,dd", new Date());
		name = "";
		id = "";
		saleDate = "";
		timeLimitProdList = new ArrayList<TimeLimitProd>();
		for (int i = 0; i < 24; i++) {
			timeLimitProdList.add(new TimeLimitProd());
		}
		return "add";
	}

	public String edit() {
		error = null;
		minDate = DateUtil.convertDateToString("yyyy,MM - 1,dd", new Date());
		TimeLimitMain tlm = timeLimitSaleService.get(Long.parseLong(id));
		id = tlm.getId().toString();
		name = tlm.getName();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		saleDate = df.format(tlm.getSaleDate());
		CommonCriteria criteria = new CommonCriteria();
		criteria.addEq("mainId", tlm.getId());
		timeLimitProdList = timeLimitSaleService.getTimeLimitProdList(criteria);
		return "edit";
	}

	public String save() {
		error = null;
		try {
			TimeLimitProd tlp;
			timeLimitProdList = new ArrayList<TimeLimitProd>();
			for (int i = 0; i < productId.length; i++) {
				if (StringUtils.isBlank(id)) {
					tlp = new TimeLimitProd();
				} else {
					tlp = timeLimitSaleService.getTimeLimitProd(prodId[i]);
				}

				tlp.setProductId(productId[i]);
				tlp.setRoundTag(roundTag[i].equals("#") ? "" : StringUtils.substring(roundTag[i], 0, 8));
				tlp.setProductName(StringUtils.substring(productName[i], 0, 40));
				tlp.setIdxProductName(idxProductName[i].equals("#") ? "" : StringUtils.substring(idxProductName[i], 0, 16));
				tlp.setImagePath(imagePath[i]);
				tlp.setIsLimitBuy(is_limit_buy[i]);
				tlp.setIsRepeat(is_repeat[i]);
				tlp.setMemberPrice(new BigDecimal(memberPrice[i]));
				tlp.setLimitPrice(new BigDecimal(limitPrice[i]));
				tlp.setAdWord(adWord[i].equals("#") ? "" : StringUtils.substring(adWord[i], 0, 25));
				timeLimitProdList.add(tlp);
			}

			// check date exist
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("saleDate", df.parse(saleDate));
			criteria.addEq("categoryID", 0);
			criteria.addNe("categoryID", -1);
			if (StringUtils.isNotBlank(id)) {
				criteria.addNe("id", Long.parseLong(id));
			}
			if (timeLimitSaleService.getListSize(criteria).intValue() > 0) {
				error = "exist";
				return "edit";
			}
			timeLimitSaleValidate();
			if (!GenerateHelper.mkDir(imageFolder)) {
				addFieldError("save error", "储存圖片失败");
				return "edit";
			}
			TimeLimitMain tlm;
			if (StringUtils.isBlank(id)) {
				tlm = new TimeLimitMain();
			} else {
				tlm = timeLimitSaleService.get(Long.parseLong(id));
			}
			DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			tlm.setSaleDate(df.parse(saleDate));
			tlm.setName(name);
			tlm.setCategoryID(0);

			int imgCount = 0;
			for (int i = 0; i < timeLimitProdList.size(); i++) {
				tlp = timeLimitProdList.get(i);
				tlp.setStartDate(df2.parse(df.format(tlm.getSaleDate()) + " " + i + ":00:00"));
				tlp.setEndDate(df2.parse(df.format(tlm.getSaleDate()) + " " + (i + 1) + ":00:00"));
				if ("Y".equals(tlp.getIsRepeat())) {
					TimeLimitProd tlpPre = timeLimitProdList.get(i - 1);
					tlp.setImagePath(tlpPre.getImagePath());
					tlp.setIsLimitBuy(tlpPre.getIsLimitBuy());
					tlp.setProductId(tlpPre.getProductId());
					tlp.setMemberPrice(tlpPre.getMemberPrice());
					tlp.setLimitPrice(tlpPre.getLimitPrice());
					tlp.setRoundTag(tlpPre.getRoundTag());
					tlp.setIdxProductName(tlpPre.getIdxProductName());
					tlp.setProductName(tlpPre.getProductName());
					tlp.setAdWord(tlpPre.getAdWord());
				} else {
					if (!"N".equals(uploadImage[i])) {
						String today = FastDateFormat.getInstance(EcConstant.DEFAULT_PATTERN_DATE).format(
								DateUtil.getToday().getTime());
						eventImage = saveImgFile(prodImg[imgCount], uploadImage[i], imageFolder);
						tlp.setImagePath(ServerValue.getImgDomain() + "/eventImg/" + today + "/" + imageFolder + "/"
								+ eventImage.getUuid() + eventImage.getImgType());
						imgCount++;
					} else {
						tlp.setImagePath(imagePath[i]);
					}
				}
			}
			timeLimitSaleService.saveTimeLimitSale(tlm, timeLimitProdList);
			id = tlm.getId().toString();
			addFieldError("", "储存成功");
			DateFormat df3 = new SimpleDateFormat("yyyyMMddHHmmss");
			timeLimitSaleService.updateData(df3.format(new Date()));
			timeLimitSaleService.generateTimeLimitSaleList(df3.format(new Date()), 0);
		} catch (Exception e) {
			addFieldError("", "储存失败 " + e.getMessage());
		}
		return "edit";
	}

	EventImage saveImgFile(File imgFile, String fileName, String advType) {
		try {
			eventImage = new EventImage();
			eventImage.setImgType(fileName.substring(fileName.lastIndexOf("."), fileName.length()));
			eventImage = timeLimitSaleService.saveEventImage(eventImage);
			boolean result = GenerateHelper.uploadImage(eventImage, imgFile, advType);
			if (result) {
				return eventImage;
			} else {
				return null;
			}
		} catch (Exception e) {
			logger.info("exception :{}", e.getMessage());
		}
		return null;
	}

	private boolean timeLimitSaleValidate() throws CoreException, ParseException, IOException {
		clearErrorsAndMessages();
		error = null;
		/**************************** 必填栏位 ****************************/
		logger.info("neme = " + name);

		if (StringUtils.isBlank(name)) {
			addFieldError("name", "请输入活动名称");
		}

		if (StringUtils.isBlank(saleDate)) {
			addFieldError("saleDate", "请输入活动日期");
		}

		for (int i = 0; i < productId.length; i++) {
			if ("Y".equals(is_repeat[i])) {
				continue;
			}
			if (StringUtils.isBlank(productId[i])) {
				addFieldError("product" + (i + 1) + "Id", "请输入商品" + (i + 1) + "编号");
			} else if (!generateService.isProductExist(productId[i])) {
				addFieldError("product" + (i + 1) + "Id", "商品" + (i + 1) + "可能不存在，或是已被删除，或是不在架上");
				error = (StringUtils.isNotBlank(error) ? error + "," + (i + 1) : Integer.toString(i + 1));
			}

			if (StringUtils.isBlank(productName[i])) {
				addFieldError("product" + (i + 1) + "Name", "请输入商品" + (i + 1) + "名称");
			}

			if (StringUtils.isBlank(memberPrice[i])) {
				addFieldError("product" + (i + 1) + "MemberPrice", "请输入商品" + (i + 1) + "会員价");
			}

			if (StringUtils.isBlank(limitPrice[i])) {
				addFieldError("product" + (i + 1) + "LimitPrice", "请输入商品" + (i + 1) + "秒杀价");
			}
		}

		if (getFieldErrors().isEmpty() && StringUtils.isBlank(error)) {
			return true;
		}
		return false;
	}

	public TimeLimitSaleService getTimeLimitSaleService() {
		return timeLimitSaleService;
	}

	public void setTimeLimitSaleService(TimeLimitSaleService timeLimitSaleService) {
		this.timeLimitSaleService = timeLimitSaleService;
	}

	public SimplePager getPager() {
		return pager;
	}

	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	public List<TimeLimitMain> getTimeLimitMainList() {
		return timeLimitMainList;
	}

	public void setTimeLimitMainList(List<TimeLimitMain> timeLimitMainList) {
		this.timeLimitMainList = timeLimitMainList;
	}

	public String getSstartDateParam() {
		return sstartDateParam;
	}

	public void setSstartDateParam(String sstartDateParam) {
		this.sstartDateParam = sstartDateParam;
	}

	public String getSendDateParam() {
		return sendDateParam;
	}

	public void setSendDateParam(String sendDateParam) {
		this.sendDateParam = sendDateParam;
	}

	public String getScategoryId() {
		return scategoryId;
	}

	public void setScategoryId(String scategoryId) {
		this.scategoryId = scategoryId;
	}

	public DomainService<Menu> getMenuService() {
		return menuService;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public Menu getShowTypeMenu() {
		return showTypeMenu;
	}

	public void setShowTypeMenu(Menu showTypeMenu) {
		this.showTypeMenu = showTypeMenu;
	}

	public String getSshowTypeParam() {
		return sshowTypeParam;
	}

	public void setSshowTypeParam(String sshowTypeParam) {
		this.sshowTypeParam = sshowTypeParam;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getSnameParam() {
		return snameParam;
	}

	public void setSnameParam(String snameParam) {
		this.snameParam = snameParam;
	}

	public List<TimeLimitProd> getTimeLimitProdList() {
		return timeLimitProdList;
	}

	public void setTimeLimitProdList(List<TimeLimitProd> timeLimitProdList) {
		this.timeLimitProdList = timeLimitProdList;
	}

	public String getSaleDate() {
		return saleDate;
	}

	public void setSaleDate(String saleDate) {
		this.saleDate = saleDate;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String[] getIs_repeat() {
		return is_repeat;
	}

	public void setIs_repeat(String[] isRepeat) {
		is_repeat = isRepeat;
	}

	public String[] getImagePath() {
		return imagePath;
	}

	public void setImagePath(String[] imagePath) {
		this.imagePath = imagePath;
	}

	public File[] getProdImg() {
		return prodImg;
	}

	public void setProdImg(File[] prodImg) {
		this.prodImg = prodImg;
	}

	public String[] getProductId() {
		return productId;
	}

	public void setProductId(String[] productId) {
		this.productId = productId;
	}

	public String[] getProductName() {
		return productName;
	}

	public void setProductName(String[] productName) {
		this.productName = productName;
	}

	public String[] getIdxProductName() {
		return idxProductName;
	}

	public void setIdxProductName(String[] idxProductName) {
		this.idxProductName = idxProductName;
	}

	public String[] getMemberPrice() {
		return memberPrice;
	}

	public void setMemberPrice(String[] memberPrice) {
		this.memberPrice = memberPrice;
	}

	public String[] getLimitPrice() {
		return limitPrice;
	}

	public void setLimitPrice(String[] limitPrice) {
		this.limitPrice = limitPrice;
	}

	public String[] getIs_limit_buy() {
		return is_limit_buy;
	}

	public void setIs_limit_buy(String[] isLimitBuy) {
		is_limit_buy = isLimitBuy;
	}

	public GenerateService getGenerateService() {
		return generateService;
	}

	public void setGenerateService(GenerateService generateService) {
		this.generateService = generateService;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public String[] getUploadImage() {
		return uploadImage;
	}

	public void setUploadImage(String[] uploadImage) {
		this.uploadImage = uploadImage;
	}

	public String[] getProdId() {
		return prodId;
	}

	public void setProdId(String[] prodId) {
		this.prodId = prodId;
	}

	public String getMinDate() {
		return minDate;
	}

	public void setMinDate(String minDate) {
		this.minDate = minDate;
	}

	public String[] getAdWord() {
		return adWord;
	}

	public void setAdWord(String[] adWord) {
		this.adWord = adWord;
	}

	public String[] getRoundTag() {
		return roundTag;
	}

	public void setRoundTag(String[] roundTag) {
		this.roundTag = roundTag;
	}

}
